from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from rest_framework import viewsets, mixins
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.hashers import make_password
# Create your views here.
from users.models import UserProfile, VerifyCode
from users.serializers import UserProfileSerializer, SmsSerializer, UserRegSerializer
from utils.aliyun.send_sms import send_sms, create_code
import uuid
import json


# 手机号也可登陆
class CustomBackend(ModelBackend):
    """
    自定义用户验证规则
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(mobile=username))
            print(make_password(password))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


# 用户
class UserProfileViewSet(mixins.CreateModelMixin,
                         mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserRegSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return UserProfileSerializer
        elif self.action == 'create':
            return UserRegSerializer
        return UserProfileSerializer

    # 创建用户不需要权限
    def get_permissions(self):
        if self.action == 'create':
            return []
        else:
            return [permissions.IsAuthenticated()]

    # 无论传入任何数据均返回当前用户信息
    def get_object(self):
        return self.request.user


# 验证码
class SmsCodeViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = SmsSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        mobile = serializer.validated_data['mobile']
        code = create_code(6)
        params = "{\"code\":\"" + code + "\"}"
        __business_id = uuid.uuid1()
        sms_status = send_sms(business_id=__business_id, phone_numbers=mobile, template_param=params)
        sms_status.decode('utf-8')
        sms_status = json.loads(sms_status)

        if sms_status['Code'] == 'OK':
            verify_code = VerifyCode(code=code, mobile=mobile)
            verify_code.save()
            return Response({'mobile': mobile}, status=status.HTTP_201_CREATED)
        else:
            return Response({'mobile': sms_status['Message']}, status=status.HTTP_400_BAD_REQUEST)

